from pysqlite2 import dbapi2 as sqlite

iterations = 200
db = sqlite.connect('database_test_11')

# clear out the current PageRank tables
db.execute('drop table if exists wordrank')
db.execute('create table wordrank(urlid primary key,score)')

# initialize every url with a PageRank of 1
db.execute('insert into wordrank select rowid, 1.0 from urllist')
db.commit( )

for i in range(iterations):
	print "Iteration %d" % (i)
	for (urlid,) in db.execute("select rowid from urllist where rowid not in (select distinct toid from link where flag=1)"):
		pr=0.15
		
		# Loop through all the pages that link to this one
		for (linker,) in db.execute('select distinct fromid from link where toid=%d' % urlid):
			
			# Get the PageRank of the linker
			linkingpr=db.execute('select score from wordrank where urlid=%d' % linker).fetchone( )[0]
			
			# Get the total number of links from the linker
			linkingcount=db.execute('select count(*) from link where fromid=%d' % linker).fetchone( )[0]
	
			pr+=0.85*(linkingpr/linkingcount)
	
		db.execute('update wordrank set score=%f where urlid=%d' % (pr,urlid))
	db.commit( )

print "calculating for dangling links"

for (urlid,) in db.execute("select rowid from urllist where rowid in (select distinct toid from link where flag=1)"):
	pr=0.15
#	for (linker,) in db.execute('select distinct fromid from link where toid=%d' % urlid):
#		linkingpr=db.execute('select score from wordrank where urlid=%d' % linker).fetchone( )[0]
#		
#		linkingcount=db.execute('select count(*) from link where fromid=%d' % linker).fetchone( )[0]
#		pr+=0.85*(linkingpr/linkingcount)
	db.execute('update wordrank set score=%f where urlid=%d' % (pr,urlid))
db.commit( )
